import jsonpath
import onnxruntime
import requests
from PIL import Image
import ddddocr
import base64
from io import BytesIO
import os


def get_auth_captcha():
    """获取验证码的接口"""
    paylod = {
        "method": "get",
        "url": os.environ['URL']+"/auth/captcha"
    }
    response = requests.request(**paylod)
    sn = jsonpath.jsonpath(response.json(), '$..sn')[0]
    image = jsonpath.jsonpath(response.json(), '$..image')[0]
    return sn, image


def dddd_ocr_text(image):
    onnxruntime.set_default_logger_severity(3)

    #步骤一：对image进行分割，分割头部和base64编码，得到base64
    encode_data = image.split(",")[1]

    #步骤二：解析base64，得到元数据
    decode_data = base64.b64decode(encode_data)

    #步骤三：通过ddddorc来识别图片的元数据，得到最终结果
    orc = ddddocr.DdddOcr()
    text = orc.classification(decode_data)
    return text

#存放全局的sn和验证码文本
sn_captcha_text = {}

#执行次数
rum_rums = 0

def get_res_sn_captcha():
    """获取sn和image最终的方法"""

    #生产环境
    if os.environ["EVN"] == "prod":

        global rum_rums

        #只有第一次执行和失败重试的第一次执行的时候才会执行
        if not sn_captcha_text or rum_rums % 2 == 0:
            sn, image = get_auth_captcha()
            captcha = dddd_ocr_text(image)
            sn_captcha_text["sn"] = sn
            sn_captcha_text["captcha"] = captcha

        rum_rums += 1
        return sn_captcha_text

    #测试环境
    elif os.environ["EVN"] == "prod":
        sn = get_auth_captcha()[0]
        sn_captcha_text["sn"] = sn
        sn_captcha_text["captcha"] = "captcha"
        return sn_captcha_text



if __name__ == '__main__':
    image = ""
    print(dddd_ocr_text(image))








